package com.gm.commonlib.module.image.takeimage;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.gm.commonlib.R;
import com.gm.commonlib.util.permission.PermissionUtil;
import com.gm.commonlib.util.permission.interfaces.IPermissionCallback;
import com.gm.commonlib.util.viewUtils.RepeatClickUtils;
import com.gm.commonlib.views.toast.ToastUtil;
import com.youth.banner.util.LogUtils;

import java.io.File;
import java.util.List;
import java.util.Set;

//选择文件操作类

public class SelectPicActivity extends Activity implements EasyPermissions.PermissionCallbacks {
    public static final String BTN_TEXT = "查看大图";
    public static final int TO_SELECT_PHOTO = 1;
    public final static int PICTURE_FROM_UNKNOWN = 0;
    public final static int PICTURE_FROM_PICK = 1;
    public final static int PICTURE_FROM_TACK = 2;

    public final static int RESULT_VIEW_ORG_PHOTO = 2;

    public final static String PICTURE_FROM = "pictureFrom";

    public final static String HIDE_TACK_PHOTO_MASK = "HideTackPhoto";
    public final static String HIDE_PICK_PHOTO_MASK = "HidePickPhoto";

    public final static String HIDE_VIEW_PHOTO_MASK = "HIDE_VIEW_Photo";

    // 期望类型
    public static final String SELECT_PIC_BY_EXPECT_TYPES = "expect_type";

    // 使用照相机拍照获取图片
    public static final int SELECT_PIC_BY_TACK_PHOTO = 1;
    // 使用相册中的图片
    public static final int SELECT_PIC_BY_PICK_PHOTO = 2;
    // 从Intent获取图片路径的KEY
    public static final String KEY_PHOTO_PATH = "photo_path";

    public static final String KEY_CANCEL_PHOTO = "cancelPhoto";
    private static final String TAG = "SelectPicActivity";
    public static final String BTN_VIEW_PHOTO_TEXT = "btn_view_photo_text";

    public static final String IMAGE_PATH="/gm/smt/temp/";

    /**
     * 获取到的图片路径
     */
    private String picPath;
    private Intent lastIntent;
    private Uri photoUri;

    View ll_take_photo;
    View ll_pick_photo;
    View ll_cancel_layout;
    View ll_view_layout;
    private TextView btn_pick_photo;
    private String[] expectType;

    private int pictureFrom = PICTURE_FROM_UNKNOWN;

    EasyPermissions.PermissionHelper mPermissionHelper = null;
    private Button btn_view_photo;
    String btn_view_photo_text;

    //context.getFilesDir().getAbsolutePath()
    /* 拍照的照片存储位置 */
    private   File PHOTO_DIR;

    public  String getInnerSDCardPath() {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            File external = getExternalFilesDir(null);
            if (external != null) {
                return external.getAbsolutePath() + File.separator;
            }
        }
        return getFilesDir().getAbsolutePath() + File.separator;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        PHOTO_DIR = new File(getInnerSDCardPath());
        super.onCreate(savedInstanceState);
        setContentView(R.layout.select_pic_layout);
        PermissionUtil.checkFileUrlPermission();

        initViews();

        if (getIntent().getBooleanExtra(HIDE_TACK_PHOTO_MASK, false)) {
            ll_take_photo.setVisibility(View.GONE);
        } else {
            ll_take_photo.setVisibility(View.VISIBLE);
        }

        if (getIntent().getBooleanExtra(HIDE_PICK_PHOTO_MASK, false)) {
            ll_pick_photo.setVisibility(View.GONE);
        } else {
            ll_pick_photo.setVisibility(View.VISIBLE);
        }

        if (getIntent().getBooleanExtra(HIDE_VIEW_PHOTO_MASK, true)) {
            ll_view_layout.setVisibility(View.GONE);
        } else {
            ll_view_layout.setVisibility(View.VISIBLE);
        }

        if (getIntent().getBooleanExtra(KEY_CANCEL_PHOTO, false)) {
            ll_cancel_layout.setVisibility(View.VISIBLE);
        } else {
            ll_cancel_layout.setVisibility(View.GONE);
        }

        mPermissionHelper = EasyPermissions.createPermissionHelper(this);

        mPermissionHelper.addCheckPermission(Manifest.permission.CAMERA,
                Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            mPermissionHelper.addCheckPermission(Manifest.permission.READ_EXTERNAL_STORAGE);
        }

        if (getIntent() != null && getIntent().getExtras() != null) {
            try {
                expectType = getIntent().getExtras().getStringArray(SELECT_PIC_BY_EXPECT_TYPES);
            } catch (Exception e) {
                expectType = null;
            }
        }
        if (savedInstanceState != null) {
            fileName = savedInstanceState.getString("fileName");
            pictureFrom = savedInstanceState.getInt(PICTURE_FROM);
        } else {
            pictureFrom = PICTURE_FROM_UNKNOWN;
        }
        lastIntent = getIntent();
        String pickPhotoTitle = getIntent().getStringExtra("pickPhotoTitle");
        if (pickPhotoTitle != null) {
            btn_pick_photo.setText(pickPhotoTitle);
        }
        btn_view_photo_text = getIntent().getStringExtra(BTN_VIEW_PHOTO_TEXT);
        if (!TextUtils.isEmpty(btn_view_photo_text)) {
            btn_view_photo.setText(btn_view_photo_text);
        }
    }

    private void initViews() {
        ll_take_photo = findViewById(R.id.ll_take_photo);
        ll_pick_photo = findViewById(R.id.ll_pick_photo);
        ll_cancel_layout = findViewById(R.id.ll_cancel_layout);
        ll_view_layout = findViewById(R.id.ll_view_layout);
        btn_pick_photo = findViewById(R.id.btn_pick_photo);
        btn_view_photo = findViewById(R.id.btn_view_photo);
        findViewById(R.id.dialog_layout).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onFinishedClicked(v);
            }
        });

        findViewById(R.id.btn_take_photo).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                btn_take_photo(v);
            }
        });
        findViewById(R.id.btn_pick_photo).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                btn_pick_photo(v);
            }
        });
        findViewById(R.id.btn_cancel_photo).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                btn_cancel_photo(v);
            }
        });
        findViewById(R.id.btn_view_photo).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                btn_view_photo(v);
            }
        });

        findViewById(R.id.btn_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                btn_cancel(v);
            }
        });
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        if (fileName != null) {
            outState.putString("fileName", fileName);
        }
        outState.putInt(PICTURE_FROM, pictureFrom);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        if (savedInstanceState != null) {
            fileName = savedInstanceState.getString("fileName");
        }
    }

    public void onFinishedClicked(View view) {
        if (RepeatClickUtils.check()) {
            return;
        }
        lastIntent.putExtra(PICTURE_FROM, pictureFrom);
        setResult(RESULT_CANCELED, lastIntent);
        finish();
    }

    public void btn_take_photo(View view) {
        if (RepeatClickUtils.check()) {
            return;
        }
        PermissionUtil.applyCameraAndFileStorePermission(this, new IPermissionCallback() {
            @Override
            public void onPermissionResult(boolean b, Set<String> set) {
                if (b){
                    takePhoto();
                }
                else {
                    ToastUtil.showToast("权限没有打开");
                }
            }
        });


    }

    public void btn_pick_photo(View view) {
        if (RepeatClickUtils.check()) {
            return;
        }

        pictureFrom = PICTURE_FROM_PICK;
        pickPhoto();
    }

    public void btn_cancel_photo(View view) {
        if (RepeatClickUtils.check()) {
            return;
        }
        lastIntent.putExtra(PICTURE_FROM, pictureFrom);
        setResult(RESULT_FIRST_USER, lastIntent);
        finish();
    }

    public void btn_view_photo(View view) {
        if (RepeatClickUtils.check()) {
            return;
        }
        lastIntent.putExtra(PICTURE_FROM, pictureFrom);
        setResult(RESULT_VIEW_ORG_PHOTO, lastIntent);
        finish();
    }

    public void btn_cancel(View view) {
        if (RepeatClickUtils.check()) {
            return;
        }
        lastIntent.putExtra(PICTURE_FROM, pictureFrom);
        setResult(RESULT_CANCELED, lastIntent);
        finish();
    }

    /**
     * 拍照获取图片
     */
            private void takePhoto() {

                // 执行拍照前，应该先判断SD卡是否存在
                String SDState = Environment.getExternalStorageState();
                if (Environment.MEDIA_MOUNTED.equals(SDState)) {
                    /***
                     * 需要说明一下，以下操作使用照相机拍照，拍照后的图片会存放在相册中的 这里使用的这种方式有一个好处就是获取的图片是拍照后的原图
                     * 如果不实用ContentValues存放照片路径的话，拍照后获取的图片为缩略图不清晰
                     */

            try {
                if (!PHOTO_DIR.exists()) {
                    boolean iscreat = PHOTO_DIR.mkdirs();// 创建照片的存储目录
                    if (!iscreat){
                        ToastUtil.showToast("创建存储目录失败111");
                        return;
                    }
                }
                fileName = System.currentTimeMillis() + ".png";
                File mPhotoFile = new File(PHOTO_DIR, fileName);
                if (!mPhotoFile.exists()) {
                 boolean isOk=   mPhotoFile.createNewFile();
                    if (!isOk){
                        ToastUtil.showToast("创建存储目录失败222");
                    }
                }
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE, null);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mPhotoFile));
                intent.putExtra(MediaStore.Images.Media.ORIENTATION, 0);
                startActivityForResult(intent, SELECT_PIC_BY_TACK_PHOTO);
            } catch (Exception e) {
                e.printStackTrace();
                ToastUtil.showToast("获取异常： "+e.toString());
            }
        } else {
            Toast.makeText(this, "内存卡不存在", Toast.LENGTH_LONG).show();
        }
    }


    /***
     * 从相册中取图片
     */
    private void pickPhoto() {
        PermissionUtil.applyCameraAndFileStorePermission(this, new IPermissionCallback() {
            @Override
            public void onPermissionResult(boolean result, Set<String> dataSet) {
                if (result) {
                    Intent intent = new Intent(Intent.ACTION_PICK, null);
                    intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                    startActivityForResult(intent, SELECT_PIC_BY_PICK_PHOTO);
                } else {
                    PermissionUtil.showNotFilePermissNt(SelectPicActivity.this);
                }
            }
        });


    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        lastIntent.putExtra(PICTURE_FROM, pictureFrom);
        setResult(RESULT_CANCELED, lastIntent);
        finish();
        return super.onTouchEvent(event);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            doPhoto(requestCode, data);
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 选择图片后，获取图片的路径
     *
     * @param requestCode
     * @param data
     */
    private void doPhoto(int requestCode, Intent data) {
        /**
         * 从相册取图片，有些手机有异常情况
         */
        if (requestCode == SELECT_PIC_BY_PICK_PHOTO) {
            if (data == null) {
                Toast.makeText(this, "选择图片文件出错", Toast.LENGTH_LONG).show();
                return;
            }
            photoUri = data.getData();
            LogUtils.d("获取数据1111: "+photoUri);
            if (photoUri == null) {
                Toast.makeText(this, "选择图片文件出错", Toast.LENGTH_LONG).show();
                return;
            }
            picPath = RealPathUtils.getPath(this, data.getData());
            Log.i(TAG, "imagePath = " + picPath);
            if (picPath != null) {
                if (expectType != null && expectType.length > 0) {
                    boolean hasExpectType = false;
                    for (String type : expectType) {
                        if (picPath.endsWith(type)) {
                            hasExpectType = true;
                            break;
                        }
                    }
                    if (!hasExpectType) {
                        String typeGroup = "";
                        for (String type : expectType) {
                            typeGroup += type;
                            typeGroup += "|";
                        }
                        if (typeGroup.contains("|")) {
                            typeGroup = typeGroup.substring(0, typeGroup.length() - 1);
                        }
                        String errorMsg = String.format("格式不正确!需要(%s)类型的文件", typeGroup);
                        Toast.makeText(this, errorMsg, Toast.LENGTH_SHORT).show();
                        return;
                    }
                }
                LogUtils.d("获取数据: "+picPath);
                lastIntent.putExtra(KEY_PHOTO_PATH, picPath);
                lastIntent.putExtra("type", SELECT_PIC_BY_PICK_PHOTO);
                lastIntent.putExtra(PICTURE_FROM, pictureFrom);
                setResult(Activity.RESULT_OK, lastIntent);
                finish();
            } else {
                Toast.makeText(this, "选择文件不正确!", Toast.LENGTH_LONG).show();
            }
        }
        if (requestCode == SELECT_PIC_BY_TACK_PHOTO) {
            if (fileName == null) {
                Toast.makeText(this, "拍照不成功!", Toast.LENGTH_LONG).show();
                return;
            }
            File f = new File(PHOTO_DIR, fileName);
            if (f.exists()) {
                lastIntent.putExtra(KEY_PHOTO_PATH, f.getAbsolutePath());
                lastIntent.putExtra("type", SELECT_PIC_BY_TACK_PHOTO);
                lastIntent.putExtra(PICTURE_FROM, pictureFrom);
                setResult(Activity.RESULT_OK, lastIntent);
                finish();
            } else {
                Toast.makeText(this, "拍照不成功!", Toast.LENGTH_LONG).show();
            }
        }
    }

    private String fileName;

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
        LogUtils.i("所有权限通过");
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
    }

    @Override
    public void onAllPermissionsGranted(int requestCode, Object mRequestParam) {

    }

    private final static int REQUEST_TACK_PHOTO = 1001;



    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        mPermissionHelper.onRequestPermissionsResult(requestCode, permissions, grantResults);
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }
}
